use std::str;
use std::error::Error;
use tokio::net::UdpSocket;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let addr = "0.0.0.0:9191";
    let socket = UdpSocket::bind(&addr).await?;
    println!("Listening on: {}", socket.local_addr()?);
    let mut buf =vec![0; 1024];
    let (n,peer) = socket.recv_from(&mut buf).await?;
    let str = str::from_utf8(&buf[..n]).unwrap().to_string();
    println!("recv: {}",str);
    let echo = echo(str ).await?;
    socket.send_to(echo.as_bytes(), peer).await?;
    Ok(())
}

use tokio::process::Command;
use std::string::FromUtf8Error;
async fn echo(arg : String) -> Result<String, Box<dyn Error>> {
    let output: std::process::Output = Command::new("examples/echo.sh")
        .arg(arg)
        .output()
        .await
        .expect("failed to execute echo.sh");
    Ok(String::from_utf8(output.stdout)?)
}